package App.Controller;

import App.Model.Contact_Message;
import App.Public.Lib.DataExport;
import App.Public.Lib.Vcard;
import App.Public.Lib.VcardReader;
import App.Public.Lib.VcardWriter;
import com.csvreader.CsvReader;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 此类是用于处理与模型和控制器有关的数据处理
 * Created by alisonyu on 17-2-1.
 */
public class DataMiddleWare
{
    /**
     * 导出Vcard数据
     * @param datas 导出的数据
     * @param path  导出的路径
     */
    public static void exportVcard(List<Contact_Message> datas,String path) throws Exception {

        try {
            //对路径进行检查，如果路径不合法则抛出异常，否则返回合法的路径
            path= DataExport.pathCheck(path,".vcf");

        } catch (Exception e) {
            //此处不处理异常，交给控制器处理
            throw e;
        }

        //如果存在重复文件则覆盖
        (new File(path)).delete();

        for(Contact_Message person:datas)
        {
            VcardWriter item=new VcardWriter();
            item.addName(person.getGiveName(),person.getFirstName());
            item.addFullName(person.getFullName());
            item.addSex(person.getSex());
            for(String email:person.getEmailList())
            {
                item.addEmail(email);
            }
            for(String phone:person.getPhoneNumberList())
            {
                item.addPhone(phone);
            }
            item.addAddress(person.getCountry_Home(),person.getProvince_Home(),person.getCity_Home(),person.getStreet_Home(),person.getPostCode_Home());
            item.addCompanyAddress(person.getCountry_Company(),person.getProvince_Company(),person.getCity_Company(),person.getStreet_Company(),person.getPostCode_Company());
            item.addTitle(person.getDepartment());
            item.addCompany(person.getCompany());
            item.addJob(person.getJob());
            item.addBirthday(person.getBirthday());
            item.addFax(person.getFax());
            item.addNickName(person.getPetName());
            item.addQQ(person.getQQ());
            try {
                item.writeVcard(path);
            } catch (IOException e) {
                //再次丢出异常给控制器处理
                throw e;
            }
        }
    }

    /**
     * 读取vcard文件，并将其转化为Contact_Message的对象数组
     * @param path vcf文件的路径
     * @return
     * @throws Exception
     */
    public static ArrayList<Contact_Message> importVcard(String path) throws Exception
    {
        try {
            //对路径进行检查，如果路径不合法则抛出异常，否则返回合法的路径
            path= DataExport.pathCheck(path,".vcf");

        } catch (Exception e) {
            //此处不处理异常，交给控制器处理
            throw e;
        }

        ArrayList<Contact_Message>res=new ArrayList<>();
        ArrayList<Vcard>vcards=new ArrayList<>();
        VcardReader reader=new VcardReader();
        try {
            vcards= reader.readVcard(path);
        } catch (Exception e) {
            throw e;
        }
        for(Vcard item:vcards)
        {
            Contact_Message o=new Contact_Message();
            o.setFullName(item.getFullName());
            o.setFirstName(item.getFirstName());
            o.setGiveName(item.getGiveName());

            o.setQQ(item.getQQ());
            o.setBirthday(item.getBirthday());
            o.setJob(item.getJob());
            o.setDepartment(item.getDepartment());
            o.setSex(item.getSex());

            o.setCity_Home(item.getCity_Home());
            o.setProvince_Home(item.getProvince_Home());
            o.setPostCode_Home(item.getPostCode_Home());
            o.setStreet_Home(item.getStreet_Home());
            o.setCountry_Home(item.getCountry_Home());

            o.setCity_Company(item.getCity_Company());
            o.setProvince_Company(item.getProvince_Company());
            o.setPostCode_Company(item.getPostCode_Company());
            o.setStreet_Company(item.getStreet_Company());
            o.setCountry_Company(item.getCountry_Company());

            o.setFax(item.getFax());
            o.setPhoneNumber(item.getPhoneNumberList());
            o.setEmail(item.getEmailList());
            res.add(o);
        }
        return res;
    }

    /**
     * 将csv里面的数据进行导入，转换为Contact_Message的对象数组
     * @param path csv文件的路径
     * @return
     * @throws IOException
     */
    public static ArrayList<Contact_Message> importCsv(String path) throws IOException {
        ArrayList<Contact_Message>res=new ArrayList<>();
        CsvReader r = new CsvReader(path, ',', Charset.forName("utf-8"));
        //读取表头
        r.readHeaders();

        while (r.readRecord())
        {
            Contact_Message person=new Contact_Message();
            for(String item:r.getHeaders())
            {
                try {
                    String setMethodName=getSetMethodName(item);
                    String[] data=parseData(r.get(item));
                        Method setMethod=person.getClass().getMethod(setMethodName,String.class);
                        for(String s:data)
                        {
                            setMethod.invoke(person,s);
                        }
                }
                catch (Exception e)
                {
                }
            }
            res.add(person);
        }
        r.close();
        return res;
    }

    private static String[] parseData(String data)
    {
        if(data.charAt(0)=='['&&data.charAt(data.length()-1)==']')
        {
            data=data.substring(1,data.length()-1);
        }
        return data.split(",",-1);
    }

    private static String getSetMethodName(String fieldName) {
        fieldName = replaceFirstCharToUpper(fieldName);
        return "set" + fieldName;
    }

    private static String replaceFirstCharToUpper(String fieldName) {
        char[] chars = new char[1];
        chars[0] = fieldName.charAt(0);
        String temp = new String(chars);
        if (chars[0] >= 'a' && chars[0] <= 'z') {
            fieldName = fieldName.replaceFirst(temp, temp.toUpperCase());
        }
        return fieldName;
    }
    public static void main(String[] args)
    {
        try {
            importCsv("testcsv.csv");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
